package hos.dialog

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.fragment.app.DialogFragment
import hos.ksl.dp2px
import hos.ksl.paddingHV
import hos.ksl.radius
import hos.ksl.radiusAll
import hos.ksl.setDialogGravity

/**
 * <p>Title: CustomDialogFragment </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-05-15 9:38
 * @version : 1.0
 */
class CustomDialogFragment @JvmOverloads constructor(
    private val rootId: Int = 0,
    private val root: View? = null,
    private val gravity: Int = Gravity.CENTER,
    private val drawable: GradientDrawable.() -> Unit = {},
    private val job: View.(fragment: Dialog?) -> Unit
) :
    DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        return dialog
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return root ?: inflater.inflate(rootId, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.apply {
            val radius = dp2px(4f).toFloat()
            val horizontal = dp2px(12f)
            val vertical = dp2px(8f)
            with(GradientDrawable()) {
                setColor(Color.WHITE)
                if (gravity == Gravity.BOTTOM) {
                    radius(
                        leftTop = radius,
                        rightTop = radius,
                    )
                } else {
                    radiusAll(radius)
                }
                paddingHV(horizontal, vertical)
                //默认样式
                drawable()
                background = this
            }
        }
        job.invoke(view, dialog)
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.setDialogGravity(gravity)
    }

}